# import asyncio
# import json
# import logging
# import websockets
# from threading import Thread
# import cv2
# from flask import Flask, request, jsonify
# from flask_cors import CORS
# import os
# from datetime import datetime
#
# # 设置日志级别为 DEBUG
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
#
# # 存储所有活动的 WebSocket 连接
# active_connections = set()
#
# # 创建一个全局的事件循环
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
#
# # 当客户端连接时调用
# async def handler(websocket, path=None):
#     logging.info(f"New connection: {id(websocket)}")
#     active_connections.add(websocket)
#     try:
#         async for message in websocket:
#             logging.info(f"Received message from {id(websocket)}: {message}")
#             await broadcast_data(json.loads(message))
#     except websockets.ConnectionClosedOK:
#         logging.info(f"Connection closed normally by client: {id(websocket)}")
#     except Exception as e:
#         logging.error(f"Error handling WebSocket connection: {e}")
#     finally:
#         active_connections.remove(websocket)
#         logging.info(f"Connection {id(websocket)} closed.")
#
#
# async def broadcast_data(message):
#     logging.info(f"Broadcasting message: {message}")
#     if active_connections:
#         await asyncio.wait([
#             ws.send(json.dumps(message))
#             for ws in active_connections
#         ], return_when=asyncio.ALL_COMPLETED)
#
# # WebSocket 服务器启动函数
# async def start_websocket():
#     logging.info("Starting WebSocket server on ws://0.0.0.0:5000")
#     async with websockets.serve(handler, "0.0.0.0", 5000):
#         await asyncio.Future()  # 阻塞，保持服务器运行
#
#
# # 创建 Flask 应用
# app = Flask(__name__)
# CORS(app)
# @app.route('/create/upload', methods=["GET", "POST"])
# def upload():
#     logging.info("Handling file upload request")
#     file = request.files.get("file")
#     if not file:
#         logging.error("No file part in the request")
#         return jsonify({"error": "No file part in the request"}), 400
#
#     upload_folder = 'upload'
#     if not os.path.exists(upload_folder):
#         os.makedirs(upload_folder)
#         logging.info(f"Created upload folder: {upload_folder}")
#
#     # 保存原始文件
#     file_path = os.path.join(upload_folder, file.filename)
#     file.save(file_path)
#     logging.info(f"File saved to {file_path}")
#
#     # 读取图像并调整分辨率（可选）
#     img = cv2.imread(file_path)
#     resized_img = cv2.resize(img, (720, 1080))
#     output_path = os.path.join(upload_folder, "resized_" + file.filename)  # 保存调整后的图片
#     cv2.imwrite(output_path, resized_img, [int(cv2.IMWRITE_JPEG_QUALITY), 20])
#     logging.info(f"Resized image saved to {output_path}")
#
#     # 获取服务器的基础 URL
#     base_url = request.url_root
#     # 构造完整的图片 URL
#     full_url = f"{base_url}{output_path.replace(os.getcwd(), '').lstrip('/')}"
#     logging.info(f"Full URL: {full_url}")
#
#     # 返回完整的图片 URL
#     return jsonify({
#         "message": "Image uploaded successfully",
#         "file_path": full_url
#     })
#
# # 在单独的线程中启动 Flask 应用
# def start_flask():
#     logging.info("Starting Flask server on http://0.0.0.0:5001")
#     app.run(debug=False, host='0.0.0.0', port=5001)
#
# # 主程序
# if __name__ == "__main__":
#     # 使用线程启动 Flask
#     flask_thread = Thread(target=start_flask)
#     flask_thread.start()
#
#     # 启动 WebSocket 服务
#     asyncio.run(start_websocket())



import json
import pandas as pd

# JSON文件路径
json_file_path = "test_results.json"

# 读取JSON文件
with open(json_file_path, "r", encoding="utf-8") as f:
    data = json.load(f)

# 将数据转换为DataFrame
df = pd.DataFrame(data)

# 将列名转换为中文
column_mapping = {
    "user_id": "用户ID",
    "request_id": "请求ID",
    "response_time": "响应时间(秒)",
    "status_code": "状态码",
    "response": "响应内容",
    "error": "错误信息"
}
df.rename(columns=column_mapping, inplace=True)

# 将响应内容中的JSON数据展开
df["翻译文本"] = df["响应内容"].apply(lambda x: x.get("translated_text", "N/A") if isinstance(x, dict) else "N/A")
df.drop(columns=["响应内容"], inplace=True)

# 将数据写入Excel文件
excel_file_path = "test_results.xlsx"
df.to_excel(excel_file_path, index=False, engine='openpyxl')

print(f"数据已成功导出到Excel文件: {excel_file_path}")